iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
Modern Web

從零開始的JS學習之路系列 第 23

[Day23] Array methods 陣列操作方法(1)

  • 分享至 

  • xImage
  •  

前面在講物件型別的時候只稍微談到陣列,而其實陣列包含很多種 methods 可以運用,這篇要來練習陣列的操作方法,讓我們來看看鄭列工具人可以做到哪些事。
關於怎麼當工具人,有興趣請詳見追求JS小姊姊系列 Day6~Day8 鄭列展現的工具力(上中下)
因為會提到 index(索引值)先複習一下 length 這個 Properties,例如我們建立一個 menu 陣列,然後透過 length 可以看裡面有幾個品項:

let menu = ["red tea", "green tea", "oolong tea", "milk tea"];
console.log(menu.length); // 4

// 透過 index 取得陣列裡的項目
let first = menu[0]; 
console.log(first); // red tea

let last = menu[menu.length - 1] // 因為索引值是從零開始所以要減 1
console.log(last); // milk tea

indexOf()、lastIndexOf()

indexOf() 可以判斷陣列裡是否包含需要的值,判斷方式由左而右,有的話回傳索引值,沒有的話回傳 -1,有兩個參數,第一個是值,第二個是從哪個索引值開始(預設為 0),而 lastIndexOf() 跟 indexOf() 一樣,只是差在由右而左。

let numarr = [4, 6, 7, 87, 8, 9, 54, 80];
numarr.indexOf(54); // 6,索引值
numarr.lastIndexOf(7); // 2,索引值

find()

將陣列裡每個元素帶入指定的函式然後做判斷,回傳第一個符合條件的元素,如果都沒有則回傳 undefined。

let numarr = [4, 6, 7, 8, 9, 12, 13];
numarr.find(a => a > 9); // 12
numarr.find(a => a < 3); // undefined

findIndex()

findIndex() 和 find() 相同,差別在他回傳的是索引值。第一個大於 3 的是 6 位於 numarr[2],而因為 numarr 內沒有比 0 小的值,所以回傳 [-1]。

let numarr = [1,2,6,8,9,10,11,16];
numarr.findIndex(a => a > 3); // 2
numarr.findIndex(e => a < 0)); // -1

forEach()

迭代陣列,用 forEach() 方法會將陣列內的每個元素,皆傳入並執行給定的函式一次。

menu.forEach(function (item, index, array) {
  console.log(item, index);
});
// red tea 0
// green tea 1
// oolong tea 2
// milk tea 3

這個 callback 函式將會把 Array 中的每一個元素作為參數,帶進本 callback 函式裡,每個元素各執行一次,接收三個參數:

  • 元素值(必填)
  • 索引值(選擇性)
  • 陣列本身(選擇性)
  • thisArg(選擇性)
arr.forEach(function callback(currentValue[, index[, array]]) {
    //your iterator
}[, thisArg]);

參考資料

Array-MDN


上一篇
[Day22] 計時器 setTimeout()
下一篇
[Day24] Array methods 陣列操作方法(2)
系列文
從零開始的JS學習之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
南國安迪
iT邦新手 3 級 ‧ 2021-10-08 21:03:05

感謝業配XDD

笑死

我要留言

立即登入留言